//
//  UIView+Additions.m
//  罗兰军
//
//  Created by 罗兰军 on 14-6-23.
//  Copyright (c) 2014年 luolanjun. All rights reserved.
//

#import "UIView+Additions.h"
#import <objc/runtime.h>

@implementation UIView (asso)

const char oldDelegateKey;
const char completionHandlerKey;

- (void)showAlertWithCompletionHandler:(void(^)(NSInteger buttonIndex))completionHandler{
    UIAlertView *alert = (UIAlertView *)self;
    
    if (completionHandler != nil) {
        id oldDelegate = objc_getAssociatedObject(self, &oldDelegateKey);
        if (oldDelegate == nil) {
            objc_setAssociatedObject(self, &oldDelegateKey, oldDelegate, OBJC_ASSOCIATION_ASSIGN);
        }
        
        oldDelegate = alert.delegate;
        
        alert.delegate = self;
        objc_setAssociatedObject(self, &completionHandlerKey, completionHandler, OBJC_ASSOCIATION_COPY);
    }
    [alert show];
}

- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex{
    UIAlertView *alert = (UIAlertView *)self;
    void (^theCompletionHandler)(NSInteger buttonIndex) = objc_getAssociatedObject(self, &completionHandlerKey);
    if (theCompletionHandler == nil) return;
    
    theCompletionHandler(buttonIndex);
    alert.delegate = objc_getAssociatedObject(self, &oldDelegateKey);
}

@end
